{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a63994ce-83d1-4c84-b372-2a1b6167f90a",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/guodong.li/virtual-venv/peft-venv-py310-cu117/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2023-07-22 15:47:42,177] [INFO] [real_accelerator.py:133:get_accelerator] Setting ds_accelerator to cuda (auto detect)\n"
     ]
    }
   ],
   "source": [
    "from transformers import AutoModelForCausalLM\n",
    "\n",
    "from peft import get_peft_config, get_peft_model, get_peft_model_state_dict, IA3Config, TaskType\n",
    "\n",
    "import torch\n",
    "from datasets import load_dataset\n",
    "import os\n",
    "from transformers import AutoTokenizer\n",
    "from torch.utils.data import DataLoader\n",
    "from transformers import default_data_collator, get_linear_schedule_with_warmup\n",
    "from tqdm import tqdm\n",
    "from datasets import load_dataset\n",
    "\n",
    "\n",
    "device = \"cuda\"\n",
    "\n",
    "model_name_or_path = \"/data/nfs/llm/model/bloomz-560m\"\n",
    "tokenizer_name_or_path = \"/data/nfs/llm/model/bloomz-560m\"\n",
    "\n",
    "\n",
    "peft_config = IA3Config(task_type=TaskType.CAUSAL_LM,\n",
    "                        target_modules=[\"query_key_value\", \"mlp.dense_4h_to_h\"],\n",
    "                        inference_mode=False, \n",
    "                        feedforward_modules=[\"mlp.dense_4h_to_h\"])\n",
    "\n",
    "\n",
    "\n",
    "dataset_name = \"twitter_complaints\"\n",
    "checkpoint_name = f\"{dataset_name}_{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}_v1.pt\".replace(\"/\", \"_\")\n",
    "text_column = \"Tweet text\"\n",
    "label_column = \"text_label\"\n",
    "max_length = 64\n",
    "lr = 3e-2\n",
    "num_epochs = 10\n",
    "batch_size = 8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "89aff2bb-0dce-4b2c-908d-5c5363eab688",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Found cached dataset raft (/home/guodong.li/data/peft/data/raft/twitter_complaints/1.1.0/79c4de1312c1e3730043f7db07179c914f48403101f7124e2fe336f6f54d9f84)\n",
      "100%|██████████| 2/2 [00:00<00:00, 732.82it/s]\n",
      "Loading cached processed dataset at /home/guodong.li/data/peft/data/raft/twitter_complaints/1.1.0/79c4de1312c1e3730043f7db07179c914f48403101f7124e2fe336f6f54d9f84/cache-0e20fff6b1d898ca.arrow\n",
      "Loading cached processed dataset at /home/guodong.li/data/peft/data/raft/twitter_complaints/1.1.0/79c4de1312c1e3730043f7db07179c914f48403101f7124e2fe336f6f54d9f84/cache-8d14a62b8a688c19.arrow\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Unlabeled', 'complaint', 'no complaint']\n",
      "DatasetDict({\n",
      "    train: Dataset({\n",
      "        features: ['Tweet text', 'ID', 'Label', 'text_label'],\n",
      "        num_rows: 50\n",
      "    })\n",
      "    test: Dataset({\n",
      "        features: ['Tweet text', 'ID', 'Label', 'text_label'],\n",
      "        num_rows: 3399\n",
      "    })\n",
      "})\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'Tweet text': '@HMRCcustomers No this is my first job',\n",
       " 'ID': 0,\n",
       " 'Label': 2,\n",
       " 'text_label': 'no complaint'}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from datasets import load_dataset\n",
    "\n",
    "# dataset = load_dataset(\"ought/raft\", dataset_name)\n",
    "dataset = load_dataset(\"/home/guodong.li/data/peft/raft/raft.py\", dataset_name, cache_dir=\"/home/guodong.li/data/peft/data\")\n",
    "\n",
    "classes = [k.replace(\"_\", \" \") for k in dataset[\"train\"].features[\"Label\"].names]\n",
    "print(classes)\n",
    "dataset = dataset.map(\n",
    "    lambda x: {\"text_label\": [classes[label] for label in x[\"Label\"]]},\n",
    "    batched=True,\n",
    "    num_proc=1,\n",
    ")\n",
    "print(dataset)\n",
    "dataset[\"train\"][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "12494f57-2445-4297-9bae-c61a3fcb878d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "target_max_length: 3\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "                                                                                          \r"
     ]
    }
   ],
   "source": [
    "# data preprocessing\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)\n",
    "if tokenizer.pad_token_id is None:\n",
    "    tokenizer.pad_token_id = tokenizer.eos_token_id\n",
    "target_max_length = max([len(tokenizer(class_label)[\"input_ids\"]) for class_label in classes])\n",
    "print(\"target_max_length:\", target_max_length)\n",
    "\n",
    "\n",
    "def preprocess_function(examples):\n",
    "    batch_size = len(examples[text_column])\n",
    "    inputs = [f\"{text_column} : {x} Label : \" for x in examples[text_column]]\n",
    "    targets = [str(x) for x in examples[label_column]]\n",
    "    model_inputs = tokenizer(inputs)\n",
    "    labels = tokenizer(targets)\n",
    "    for i in range(batch_size):\n",
    "        sample_input_ids = model_inputs[\"input_ids\"][i]\n",
    "        label_input_ids = labels[\"input_ids\"][i] + [tokenizer.pad_token_id]\n",
    "        # print(i, sample_input_ids, label_input_ids)\n",
    "        model_inputs[\"input_ids\"][i] = sample_input_ids + label_input_ids\n",
    "        labels[\"input_ids\"][i] = [-100] * len(sample_input_ids) + label_input_ids\n",
    "        model_inputs[\"attention_mask\"][i] = [1] * len(model_inputs[\"input_ids\"][i])\n",
    "    # print(model_inputs)\n",
    "    for i in range(batch_size):\n",
    "        sample_input_ids = model_inputs[\"input_ids\"][i]\n",
    "        label_input_ids = labels[\"input_ids\"][i]\n",
    "        model_inputs[\"input_ids\"][i] = [tokenizer.pad_token_id] * (\n",
    "            max_length - len(sample_input_ids)\n",
    "        ) + sample_input_ids\n",
    "        model_inputs[\"attention_mask\"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs[\n",
    "            \"attention_mask\"\n",
    "        ][i]\n",
    "        labels[\"input_ids\"][i] = [-100] * (max_length - len(sample_input_ids)) + label_input_ids\n",
    "        model_inputs[\"input_ids\"][i] = torch.tensor(model_inputs[\"input_ids\"][i][:max_length])\n",
    "        model_inputs[\"attention_mask\"][i] = torch.tensor(model_inputs[\"attention_mask\"][i][:max_length])\n",
    "        labels[\"input_ids\"][i] = torch.tensor(labels[\"input_ids\"][i][:max_length])\n",
    "    model_inputs[\"labels\"] = labels[\"input_ids\"]\n",
    "    return model_inputs\n",
    "\n",
    "\n",
    "processed_datasets = dataset.map(\n",
    "    preprocess_function,\n",
    "    batched=True,\n",
    "    num_proc=1,\n",
    "    remove_columns=dataset[\"train\"].column_names,\n",
    "    load_from_cache_file=False,\n",
    "    desc=\"Running tokenizer on dataset\",\n",
    ")\n",
    "\n",
    "train_dataset = processed_datasets[\"train\"]\n",
    "eval_dataset = processed_datasets[\"train\"]\n",
    "\n",
    "\n",
    "train_dataloader = DataLoader(train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)\n",
    "eval_dataloader = DataLoader(eval_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "35d44b0c-1ec8-4ac2-8a94-f91af0639fa2",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "                                                                                           \r"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input_ids': tensor([[     3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "          227985,   5484,    915,   2566,  74757,  64626,  12384,  44639,    613,\n",
       "           52282,   2670,  79920,   3344,   1002,    368,  17646,  14472,   8348,\n",
       "             664,    718,      4,  19036,     17,  31849,     17,   6312,     76,\n",
       "              44,  62470,     56,     91,     50,  14839,     21,  77658,    915,\n",
       "             210],\n",
       "         [     3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3, 227985,   5484,    915,    405, 187059,\n",
       "            2256,    664,   2550,  18833,  18607, 162467,      4,   1387,   6199,\n",
       "            3291,  23405,    613,   4657,  17082,    566,   3432,    368,  78851,\n",
       "            1185,  61273,  23181,   1553,  15596,    212, 116057,  77658,    915,\n",
       "             210],\n",
       "         [     3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3, 227985,   5484,\n",
       "             915,  39762,   2566,  22253,   6201,  75701,     15,    632,    718,\n",
       "            5840,  10006,   6201,  18881,    427,   3804,  19528,    267, 158974,\n",
       "            1320,    368,  10029,    632,  49666,     92,     34,  77658,    915,\n",
       "             210],\n",
       "         [     3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3, 227985,   5484,    915,   2566, 104565,   8695,   2089,   6140,\n",
       "          109676,  99579,   1369,    512,    368,   4570,     54,    632,    368,\n",
       "            1503, 241485, 132226,     15,    982,    727,   1152,  18100,    861,\n",
       "           32596,  77597, 168154,   1306, 132226,   4346,  87843,     17, 130462,\n",
       "             364,  32923,     89,     53,   8309,     20,     75,  77658,    915,\n",
       "             210],\n",
       "         [     3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3, 227985,   5484,    915,   2566,\n",
       "           14173,   2960,  29906,    387,  20706,  49337,   1369,  77658,    915,\n",
       "             210],\n",
       "         [     3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3, 227985,   5484,    915,   2566, 219553,  45736,\n",
       "           36876,   1713,     72,    707, 187205,  13002, 177324,  77658,    915,\n",
       "             210],\n",
       "         [     3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3, 227985,   5484,    915,   2566, 233938,  28518,  13716,\n",
       "             427,  28146,   1119,  17918,     17, 236706,    368, 214997,   7555,\n",
       "           48659,   5276,  21600,    343,     17,  51416,  22403,    318,   1531,\n",
       "            1306,   1130,  20934,    567, 101161, 184849,  87843,     17,   1594,\n",
       "           15231,   2052,  16642,     20,   7180,     80,     26,  77658,    915,\n",
       "             210],\n",
       "         [     3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "               3,      3,      3,      3,      3,      3,      3,      3,      3,\n",
       "          227985,   5484,    915,   2566,     80,   2068,    479,   2566,     80,\n",
       "            1376,    878, 147587,   3904,    632,    368,   6084,  65673,  78851,\n",
       "           11736,  15527,  19082,  33151,    461,     17,  45575,  17887,    632,\n",
       "            5219,  14216,  68870,   5967,   1841,   4346,  87843,     17,   1594,\n",
       "           14512,     27,     71,   8184,     19,    290,  63748,  77658,    915,\n",
       "             210]]),\n",
       " 'attention_mask': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n",
       "         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n",
       "         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n",
       "         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n",
       "         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n",
       "         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n",
       "         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n",
       "         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def test_preprocess_function(examples):\n",
    "    batch_size = len(examples[text_column])\n",
    "    inputs = [f\"{text_column} : {x} Label : \" for x in examples[text_column]]\n",
    "    model_inputs = tokenizer(inputs)\n",
    "    # print(model_inputs)\n",
    "    for i in range(batch_size):\n",
    "        sample_input_ids = model_inputs[\"input_ids\"][i]\n",
    "        model_inputs[\"input_ids\"][i] = [tokenizer.pad_token_id] * (max_length - len(sample_input_ids)) + sample_input_ids\n",
    "        model_inputs[\"attention_mask\"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs[\"attention_mask\"][i]\n",
    "        \n",
    "        model_inputs[\"input_ids\"][i] = torch.tensor(model_inputs[\"input_ids\"][i][:max_length])\n",
    "        model_inputs[\"attention_mask\"][i] = torch.tensor(model_inputs[\"attention_mask\"][i][:max_length])\n",
    "    return model_inputs\n",
    "\n",
    "\n",
    "test_dataset = dataset[\"test\"].map(\n",
    "    test_preprocess_function,\n",
    "    batched=True,\n",
    "    num_proc=1,\n",
    "    remove_columns=dataset[\"train\"].column_names,\n",
    "    load_from_cache_file=False,\n",
    "    desc=\"Running tokenizer on dataset\",\n",
    ")\n",
    "\n",
    "test_dataloader = DataLoader(test_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)\n",
    "next(iter(test_dataloader))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2a2bc53a-478e-4551-814b-bdbbb3725aa8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "trainable params: 172,032 || all params: 559,386,624 || trainable%: 0.0307536849504646\n"
     ]
    }
   ],
   "source": [
    "model = AutoModelForCausalLM.from_pretrained(model_name_or_path)\n",
    "\n",
    "\n",
    "\n",
    "model = get_peft_model(model, peft_config)\n",
    "model.print_trainable_parameters()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "00bcf0da-6ad7-4451-a1d4-0c4d143235ab",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PeftModelForCausalLM(\n",
       "  (base_model): IA3Model(\n",
       "    (model): BloomForCausalLM(\n",
       "      (transformer): BloomModel(\n",
       "        (word_embeddings): Embedding(250880, 1024)\n",
       "        (word_embeddings_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "        (h): ModuleList(\n",
       "          (0): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (1): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (2): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (3): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (4): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (5): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (6): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (7): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (8): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (9): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (10): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (11): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (12): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (13): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (14): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (15): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (16): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (17): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (18): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (19): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (20): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (21): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (22): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (23): BloomBlock(\n",
       "            (input_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (self_attention): BloomAttention(\n",
       "              (query_key_value): Linear(\n",
       "                in_features=1024, out_features=3072, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 3072x1])\n",
       "              )\n",
       "              (dense): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "              (attention_dropout): Dropout(p=0.0, inplace=False)\n",
       "            )\n",
       "            (post_attention_layernorm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "            (mlp): BloomMLP(\n",
       "              (dense_h_to_4h): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "              (gelu_impl): BloomGelu()\n",
       "              (dense_4h_to_h): Linear(\n",
       "                in_features=4096, out_features=1024, bias=True\n",
       "                (ia3_l): ParameterDict(  (default): Parameter containing: [torch.FloatTensor of size 1x4096])\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "        )\n",
       "        (ln_f): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n",
       "      )\n",
       "      (lm_head): Linear(in_features=1024, out_features=250880, bias=False)\n",
       "    )\n",
       "  )\n",
       ")"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "efaa1106-7356-4597-a149-cc7643731533",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'default': IA3Config(peft_type=<PeftType.IA3: 'IA3'>, auto_mapping=None, base_model_name_or_path='/data/nfs/llm/model/bloomz-560m', revision=None, task_type=<TaskType.CAUSAL_LM: 'CAUSAL_LM'>, inference_mode=False, target_modules=['query_key_value', 'mlp.dense_4h_to_h'], feedforward_modules=['mlp.dense_4h_to_h'], fan_in_fan_out=False, modules_to_save=None, init_ia3_weights=True)}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.peft_config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "4a546452-e128-40fa-b72c-ba557d17a9f7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# model\n",
    "# optimizer and lr scheduler\n",
    "optimizer = torch.optim.AdamW(model.parameters(), lr=lr)\n",
    "lr_scheduler = get_linear_schedule_with_warmup(\n",
    "    optimizer=optimizer,\n",
    "    num_warmup_steps=0,\n",
    "    num_training_steps=(len(train_dataloader) * num_epochs),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b91ef03f-609e-4d2f-9f14-cc219f20c7a4",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:01<00:00,  5.03it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 22.78it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=0: train_ppl=tensor(2.4646e+10, device='cuda:0') train_epoch_loss=tensor(23.9279, device='cuda:0') eval_ppl=tensor(195.1290, device='cuda:0') eval_epoch_loss=tensor(5.2737, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:00<00:00, 11.21it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 23.23it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=1: train_ppl=tensor(112.6432, device='cuda:0') train_epoch_loss=tensor(4.7242, device='cuda:0') eval_ppl=tensor(46.6624, device='cuda:0') eval_epoch_loss=tensor(3.8429, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:00<00:00, 10.88it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 22.53it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=2: train_ppl=tensor(37.6138, device='cuda:0') train_epoch_loss=tensor(3.6274, device='cuda:0') eval_ppl=tensor(21.8593, device='cuda:0') eval_epoch_loss=tensor(3.0846, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:00<00:00, 11.28it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 23.16it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=3: train_ppl=tensor(17.3817, device='cuda:0') train_epoch_loss=tensor(2.8554, device='cuda:0') eval_ppl=tensor(9.3968, device='cuda:0') eval_epoch_loss=tensor(2.2404, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:00<00:00, 11.34it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 22.91it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=4: train_ppl=tensor(6.2920, device='cuda:0') train_epoch_loss=tensor(1.8393, device='cuda:0') eval_ppl=tensor(3.8994, device='cuda:0') eval_epoch_loss=tensor(1.3608, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:00<00:00, 11.29it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 23.15it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=5: train_ppl=tensor(2.7512, device='cuda:0') train_epoch_loss=tensor(1.0120, device='cuda:0') eval_ppl=tensor(1.8104, device='cuda:0') eval_epoch_loss=tensor(0.5936, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:00<00:00, 11.31it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 23.19it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=6: train_ppl=tensor(1.5378, device='cuda:0') train_epoch_loss=tensor(0.4303, device='cuda:0') eval_ppl=tensor(1.2499, device='cuda:0') eval_epoch_loss=tensor(0.2231, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:00<00:00, 11.29it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 22.97it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=7: train_ppl=tensor(1.1984, device='cuda:0') train_epoch_loss=tensor(0.1810, device='cuda:0') eval_ppl=tensor(1.1350, device='cuda:0') eval_epoch_loss=tensor(0.1267, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:00<00:00, 10.71it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 23.24it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=8: train_ppl=tensor(1.1170, device='cuda:0') train_epoch_loss=tensor(0.1106, device='cuda:0') eval_ppl=tensor(1.0947, device='cuda:0') eval_epoch_loss=tensor(0.0905, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 7/7 [00:00<00:00, 11.29it/s]\n",
      "100%|██████████| 7/7 [00:00<00:00, 22.97it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=9: train_ppl=tensor(1.0917, device='cuda:0') train_epoch_loss=tensor(0.0877, device='cuda:0') eval_ppl=tensor(1.0843, device='cuda:0') eval_epoch_loss=tensor(0.0809, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "# training and evaluation\n",
    "model = model.to(device)\n",
    "\n",
    "for epoch in range(num_epochs):\n",
    "    model.train()\n",
    "    total_loss = 0\n",
    "    for step, batch in enumerate(tqdm(train_dataloader)):\n",
    "        batch = {k: v.to(device) for k, v in batch.items()}\n",
    "        #         print(batch)\n",
    "        #         print(batch[\"input_ids\"].shape)\n",
    "        outputs = model(**batch)\n",
    "        loss = outputs.loss\n",
    "        total_loss += loss.detach().float()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "        lr_scheduler.step()\n",
    "        optimizer.zero_grad()\n",
    "\n",
    "    model.eval()\n",
    "    eval_loss = 0\n",
    "    eval_preds = []\n",
    "    for step, batch in enumerate(tqdm(eval_dataloader)):\n",
    "        batch = {k: v.to(device) for k, v in batch.items()}\n",
    "        with torch.no_grad():\n",
    "            outputs = model(**batch)\n",
    "        loss = outputs.loss\n",
    "        eval_loss += loss.detach().float()\n",
    "        eval_preds.extend(\n",
    "            tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(), skip_special_tokens=True)\n",
    "        )\n",
    "\n",
    "    eval_epoch_loss = eval_loss / len(eval_dataloader)\n",
    "    eval_ppl = torch.exp(eval_epoch_loss)\n",
    "    train_epoch_loss = total_loss / len(train_dataloader)\n",
    "    train_ppl = torch.exp(train_epoch_loss)\n",
    "    print(f\"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "67687ddb-7ad0-4609-bcf7-d530cb00631c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hey @nytimes your link to cancel my subscription isn't working and nobody is answering the chat. Please don't play that kind of stupid game.\n",
      "{'input_ids': tensor([[227985,   5484,    915,  54078,   2566,   7782,  24502,   2632,   8989,\n",
      "            427,  36992,   2670, 140711,  21994,  10789,    530,  88399,    632,\n",
      "         183542,    368,  44799,     17,  29901,   5926,   7229,    861,  11596,\n",
      "            461,  78851,  14775,     17,  77658,    915,    210]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
      "         1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}\n",
      "tensor([[227985,   5484,    915,  54078,   2566,   7782,  24502,   2632,   8989,\n",
      "            427,  36992,   2670, 140711,  21994,  10789,    530,  88399,    632,\n",
      "         183542,    368,  44799,     17,  29901,   5926,   7229,    861,  11596,\n",
      "            461,  78851,  14775,     17,  77658,    915,    210,  16449,   5952,\n",
      "              3]], device='cuda:0')\n",
      "[\"Tweet text : Hey @nytimes your link to cancel my subscription isn't working and nobody is answering the chat. Please don't play that kind of stupid game. Label : complaint\"]\n"
     ]
    }
   ],
   "source": [
    "# 模型评估\n",
    "model.eval()\n",
    "i = 16\n",
    "inputs = tokenizer(f'{text_column} : {dataset[\"test\"][i][\"Tweet text\"]} Label : ', return_tensors=\"pt\")\n",
    "print(dataset[\"test\"][i][\"Tweet text\"])\n",
    "print(inputs)\n",
    "\n",
    "with torch.no_grad():\n",
    "    inputs = {k: v.to(device) for k, v in inputs.items()}\n",
    "    outputs = model.generate(\n",
    "        input_ids=inputs[\"input_ids\"], attention_mask=inputs[\"attention_mask\"], max_new_tokens=10, eos_token_id=3\n",
    "    )\n",
    "    print(outputs)\n",
    "    print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "0f2a4aaa-49e6-466a-8eb6-6a6703390a8d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "model_output: /data/nfs/llm/model/bloomz-560m_IA3_CAUSAL_LM\n"
     ]
    }
   ],
   "source": [
    "# saving model\n",
    "peft_model_id = f\"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}\"\n",
    "print(\"model_output:\", peft_model_id)\n",
    "model.save_pretrained(peft_model_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "01c3a030-9336-45ee-b7e0-716223f76422",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
      "To disable this warning, you can either:\n",
      "\t- Avoid using `tokenizers` before the fork if possible\n",
      "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n",
      "692K\t/data/nfs/llm/model/bloomz-560m_IA3_CAUSAL_LM/adapter_model.bin\n",
      "--------------\n",
      "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
      "To disable this warning, you can either:\n",
      "\t- Avoid using `tokenizers` before the fork if possible\n",
      "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n",
      "/data/nfs/llm/model/bloomz-560m_IA3_CAUSAL_LM\n",
      "├── [ 398]  adapter_config.json\n",
      "├── [689K]  adapter_model.bin\n",
      "└── [ 129]  README.md\n",
      "\n",
      "0 directories, 3 files\n"
     ]
    }
   ],
   "source": [
    "ckpt = f\"{peft_model_id}/adapter_model.bin\"\n",
    "!du -h $ckpt\n",
    "print(\"--------------\")\n",
    "!tree -h $peft_model_id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "97363c9e-5aef-41d6-a2b7-9492f558c058",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "model_input: /data/nfs/llm/model/bloomz-560m_IA3_CAUSAL_LM\n"
     ]
    }
   ],
   "source": [
    "from peft import PeftModel, PeftConfig\n",
    "\n",
    "peft_model_id = f\"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}\"\n",
    "print(\"model_input:\", peft_model_id)\n",
    "\n",
    "config = PeftConfig.from_pretrained(peft_model_id)\n",
    "model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path)\n",
    "model = PeftModel.from_pretrained(model, peft_model_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "ea98ae02-dcf5-401d-989a-3155cfd44976",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "@greateranglia Ok thanks...\n",
      "{'input_ids': tensor([[227985,   5484,    915,   2566,  14173,   2960,  29906,    387,  20706,\n",
      "          49337,   1369,  77658,    915,    210]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}\n",
      "tensor([[227985,   5484,    915,   2566,  14173,   2960,  29906,    387,  20706,\n",
      "          49337,   1369,  77658,    915,    210,   1936, 106863,      3]],\n",
      "       device='cuda:0')\n",
      "['Tweet text : @greateranglia Ok thanks... Label : no complaint']\n"
     ]
    }
   ],
   "source": [
    "model.to(device)\n",
    "model.eval()\n",
    "i = 4\n",
    "inputs = tokenizer(f'{text_column} : {dataset[\"test\"][i][\"Tweet text\"]} Label : ', return_tensors=\"pt\")\n",
    "print(dataset[\"test\"][i][\"Tweet text\"])\n",
    "print(inputs)\n",
    "\n",
    "with torch.no_grad():\n",
    "    inputs = {k: v.to(device) for k, v in inputs.items()}\n",
    "    outputs = model.generate(\n",
    "        input_ids=inputs[\"input_ids\"], attention_mask=inputs[\"attention_mask\"], max_new_tokens=10, eos_token_id=3\n",
    "    )\n",
    "    print(outputs)\n",
    "    print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "939ed30a-3ace-4419-8bd6-c2927dd92986",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
